package com.hontech.bv.task

import android.view.View
import kotlinx.coroutines.*


val appScope = CoroutineScope(Job() + Dispatchers.Main)

inline fun runApp(crossinline cb: suspend () -> Unit ) {
    appScope.launch {
        cb()
    }
}

fun safeRunApp(cb: suspend () -> Unit) {
    appScope.launch {
        try {
            cb()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun View.onClick(cb: suspend () -> Unit) {
    this.setOnClickListener { runApp(cb) }
}

fun View.onClickSafe(cb: suspend () -> Unit) {
    this.setOnClickListener { safeRunApp(cb) }
}

suspend fun<T> CompletableDeferred<T>.await(timeout: Long): T {
    return withTimeout(timeout) { await() }
}


